package com.stu.action.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.stu.entity.base.BaseEntity;
import com.stu.service.base.IBaseService;
import com.stu.service.permission.IPermissionUserService;
import com.stu.service.permission.IUserService;
import com.stu.service.sys.ISysLogService;
import com.stu.service.test.ITestService;
import com.stu.utils.CommonUtils;
import com.stu.utils.DateUtil;
import com.stu.utils.JedisUtils;
import com.stu.utils.ListTranscoder;
import com.stu.utils.LoggerUtils;
import com.stu.utils.ObjectsTranscoder;
import com.stu.utils.RedisClient;

/**
 * action 基类
 * @author lijian
 *
 * @param <T> PO
 * @param <K> service 接口
 * LoggerUtils 接口，只要实现了这个接口就要记录日志信息，相当于日志信息的开关接口
 */
@Scope("prototype")
public abstract class BaseAction<T extends BaseEntity,K extends IBaseService<T>> extends ActionSupport implements ModelDriven<T>,LoggerUtils{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected String id;
	
	protected String ids; 
	
	protected T model;
	protected K service;
	
	//参数查询
//	protected String hql;
//	protected Map<String,Object>params=new HashMap<String,Object>();
	
	protected int rows=10;//每页显示的记录数
	protected int page=1;//当前页
	protected String order;// 'asc' or 'desc'
	protected String sort;// 按照哪种属性排序
	
	protected String fr;
	
	protected JedisUtils<T> jedisUtils=new JedisUtils<T>();
	protected RedisClient redisClient=RedisClient. getInstance();
	protected ObjectsTranscoder<T> objTranscoder =  new ObjectsTranscoder<T>();
	protected ListTranscoder<T> listTranscoder = new ListTranscoder<T>();
	
	
	@Autowired
	public void setService(K service) {
		this.service = service;
	}
	
	//================ 实现 ModelDriven 的支持============//
	
	public BaseAction(){
		try {
			ParameterizedType pt=(ParameterizedType)this.getClass().getGenericSuperclass();
			@SuppressWarnings("unchecked")
			Class<T>clazz=(Class<T>)pt.getActualTypeArguments()[0];
			model=clazz.newInstance();
		} catch (Exception e) {
			logger.error(e);
			throw new RuntimeException(e);
		}
	}
	
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}
	
	protected String getSimpleClazz() {
		return (String) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getClass().getSimpleName();
	}
	
	protected Date formatCreateTime(Date date){
		return DateUtil.dtlong14FromStr(date+"");
	}
	
	//=======================  CRUD   ===========================//
	
	public Serializable save(){
		Serializable s=null;
		try {
			logger.info("save -- "+model);
			s=service.save(model);// return id 
		} catch (SQLException e) {
			logger.error(e.getMessage());
			System.err.println(e);
		}
		return s;
	}
	
	public boolean deleteByIds(){
		boolean flag=false;
		try {
			logger.warn("delete -- "+ids);
			flag=service.deleteIds(ids);
		} catch (SQLException e) {
			logger.error(e);
			System.err.println(e);
		}
		return flag;
	}
	
	public boolean update(){
		boolean flag=false;
		try {
			logger.warn("update -- "+model);
			flag=service.update(model);
		} catch (SQLException e) {
			logger.error(e);
			System.err.println(e);
		}
		return flag;
	}
	
	
	public T findById(String id){
		T t=null;
		try {
			logger.info(CommonUtils.getSessionAttribute("currentUser")+"getbyid -- "+model);
			t=service.findById(id);
		} catch (SQLException e) {
			logger.error(e);
			System.err.println(e);
		}
		return t;
	}
	
	public List<T>findByHql(String hql,Map<String,Object>params){
		List<T>entityList=new ArrayList<T>();
		try {
			logger.info("findbyhql -- "+hql+" params : "+params);
			entityList=service.find(hql, params, page, rows);
		} catch (SQLException e) {
			logger.error(e);
			System.err.println(e);
		}
		return entityList;
	}
	
	public List<T>findAll(){
		List<T>entityList=new ArrayList<T>();
		try {
			entityList=service.find();
			logger.info("findall"+entityList);
		} catch (SQLException e) {
			logger.error(e);
			System.err.println(e);
		}
		return entityList;
	}
	
	public int getAccount(String hql,Map<String,Object>params){
		int account=0;
		try {
			logger.info("getAccount -- "+hql+" params : "+params);
			account=service.count(hql, params);
		} catch (SQLException e) {
			logger.error(e);
			System.err.println(e);
		}
		return account;
	}
	
	//================ 实现 Service 实例 的支持============//
	@Resource
	protected ITestService test;
	
	@Resource
	protected ISysLogService logService;
	
	@Resource
	protected IUserService userService;
	
	@Resource
	protected IPermissionUserService permissionUserService;
	
//	@Resource
//	protected DepartmentService departmentService;
//	
//	@Resource
//	protected RoleService roleService;
//	
//	@Resource
//	protected UserService userService;
//	
//	@Resource
//	protected PrivilegeService privilegeService;
	
	
	//=================== getter and  setter ===========================//
	public T getModel() {
		return model;
	}
	public int getRows() {
		return rows;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public String getOrder() {
		return order;
	}
	public void setOrder(String order) {
		this.order = order;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public String getIds() {
		return ids;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getFr() {
		return fr;
	}

	public void setFr(String fr) {
		this.fr = fr;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	
}
